package com.seestech.sell.web.goods;

import com.github.pagehelper.Page;
import com.seestech.sell.domain.model.*;
import com.seestech.sell.common.annotation.Duplicate;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.IBrandService;
import com.seestech.sell.service.IGoodsService;
import com.seestech.sell.service.IGridService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created by idiot on 2017/6/17.
 */
@Controller
@RequestMapping(value = "goods")
public class GoodsController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private IGoodsService goodsService;
    @Resource
    private IBrandService brandService;
    @Resource
    private IGridService gridService;
    @Resource
    private ApplicationConfig applicationConfig;

    //加载page页面
    @RequiresPermissions(value = "goods:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        logger.info("加载商品页面信息=====》》》");
        return "goods/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Goods info, Model model){
        User user = getUser();
        if(user == null){
            logger.error("获取品牌信息======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        info.setStatus(StatusEnums.VALID.getValue());
        Page<Goods> lists = goodsService.getAllGoodses(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "goods/data";
    }


    //获取商品信息
    @RequestMapping(value = "getAllGoodses.json")
    @ResponseBody
    public Object getAllGoodses(Goods info, Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize){
        info.setStatus(StatusEnums.VALID.getValue());
        Page<Goods> goodses = goodsService.getAllGoodses(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        ResultBean<Object> resultBean = ResponseUtils.initResultBean(goodses, Constants.ResponseCode.success, "成功", true);
        resultBean.setTotalCount((int) goodses.getTotal());
        return resultBean;
    }

    //加载编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model){
        Brand info = new Brand();
        info.setStatus(StatusEnums.VALID.getValue());
        List<Brand> brands = brandService.getBrands(info);
        model.addAttribute("brands", brands);
        return "goods/update";
    }

    //编辑信息
    @Duplicate
    @RecordLog(value = "修改商品信息")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(Goods info){
        if(info.getCode() == null)
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "无效的商品编号");
        //menuId为空/0时表示   新增操作
        if(info.getGoodsId() == null){
            Goods goods = goodsService.getGoodsByCode(info.getCode());
            if(goods != null) {
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "编辑商品失败，商品编号已经存在");
                return;
            }
            info.setCreateUser(getUser().getUserId());
            goodsService.insert(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增商品信息成功");
        }else {     //修改操作
            List<Goods> goodses = goodsService.getGoodsesByCode(info.getCode());
            if(goodses != null && goodses.size() == 1) {
                //获取第一个  判断主键是否相同  相同就允许修改
                Goods goods = goodses.get(0);
                if(!goods.getGoodsId().equals(info.getGoodsId())) {
                    ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "编辑商品失败，商品编号已经存在");
                    return;
                }
            }else if(goodses != null && goodses.size() > 1) {
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "编辑商品失败，商品编号已经存在");
                return;
            }
            info.setUpdateUser(getUser().getUserId());
            goodsService.update(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改商品信息成功");
        }
    }


    //加载编辑页面
    @RequestMapping(value = "{goodsId}/toUpdate", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("goodsId") Long goodsId, Model model){
        Brand info = new Brand();
        info.setStatus(StatusEnums.VALID.getValue());
        List<Brand> brands = brandService.getBrands(info);
        model.addAttribute("brands", brands);
        Goods goods = goodsService.getGoodsByGoodsId(goodsId);
        model.addAttribute("goods",goods);
        return "goods/update";
    }

    //删除品牌信息
    @RecordLog(value = "删除商品信息")
    @RequestMapping(value = "{goodsId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("goodsId") Long goodsId){
        Long[] goodsIds = new Long[]{goodsId};
        List<Grid> list = gridService.getGridsByGoodsIds(goodsIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该商品已经绑定柜格信息，不能删除");
        }else {
            goodsService.delete(goodsId);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "删除商品信息成功");
        }
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] goodsIds){
        List<Grid> list = gridService.getGridsByGoodsIds(goodsIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该商品已经绑定柜格信息，不能删除");
        }else {
            goodsService.deleteBatch(goodsIds);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "批量删除商品信息成功");
        }
    }

    /**
     * @description  上传商品图片
     * @param key  文件的name属性
     */
    @PostMapping(value = "uploadImage")
    public void uploadGoodsImage(String key){
        logger.info("上传商品图片============>>>>>>开始");
        String result = uploadImage(applicationConfig, Constants.Regular.my_goods_image, key);
        if(result != null && !"".equals(result))
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), result);
        else
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "上传失败");
    }

}
